﻿<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using Activity;
using Activity.Helper;
using System.Configuration;
using Activity.Data;
using Activity.API;

public class ImageHandler : BaseHandler
{
    #region 按业务上传/删除/获取图片
    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="BiType">业务类型</param>
    /// <returns>kmImages</returns>
    public void UploadOSS()
    {
        try
        {
            //string BiType = _httpReuqest["BiType"];
            string Path_h = "Inspection";
            if (string.IsNullOrWhiteSpace(Path_h)) Error("未找到上传路径");
            string imgPath = string.Empty;

            var bucketName = ConfigurationManager.AppSettings["image-oss-BucketName"];

            if ((this.Request.Headers.AllKeys.Contains("X_FILENAME") && this.Request["X_FILENAME"] == "AJAX")
        || (this.Request.Headers.Get("X_FILENAME") == null ? "" : this.Request.Headers.Get("X_FILENAME")) == "AJAX" || (this.Request.Headers.AllKeys.Contains("X_filename") && this.Request.Headers["X_filename"] == "AJAX"))
            {
                #region 单个文件上传
                var length = Request.ContentLength;
                //Image drimg = Image.FromStream(Request.InputStream);
                //var bytes = ImageThumbnailHelper.GenerateHighThumbnail(drimg, out int w, out int h);
                string fn = string.Empty;
                string toSave = string.Empty;
                using (System.Drawing.Image drimg = System.Drawing.Image.FromStream(Request.InputStream))
                {
                    // var bm = new Bitmap(drimg);
                    var parcent = ImageThumbnailHelper.SizeImageWithOldPercent(drimg, 1, 1);
                    var bytes = Bitmap2Byte(parcent);
                    var name = DateTime.Now.Ticks.ToString();
                    var taskTypeParam = _httpReuqest.Get("taskType");
                    fn = this._httpReuqest.Get("fn") == null ? name : this._httpReuqest.Get("fn");
                    var v_path = GetSavaFilePath("INSPECTION");
                    toSave = getFileName(v_path, fn);
                    ImageHelper.SavaOss(bucketName, toSave, bytes);
                }
                var img = new kmImages()
                {
                    ID = Guid.NewGuid(),
                    Title = fn,
                    Url = toSave,
                    BucketName = bucketName,
                };
                using (var dc = new ActivityEntities())
                {
                    dc.kmImages.Add(img);
                    dc.SaveChanges();
                }
                img.Url = ImageHelper.GetOssUrl(bucketName, img.Url);
                Success(img);
                #endregion
            }
            else
            {
                #region 多文件上传
                var imgList = new List<kmImages>();
                for (var i = 0; i < Request.Files.Count; i++)
                {
                    var postFile = Request.Files[i];
                    var path = GetSavaFilePath("INSPECTION");
                    using (System.Drawing.Image drimg = System.Drawing.Image.FromStream(postFile.InputStream))
                    {
                        #region 图片压缩
                        // var bm = new Bitmap(drimg);
                        var parcent = ImageThumbnailHelper.SizeImageWithOldPercent(drimg, 1, 1);
                        var bytes = Bitmap2Byte(parcent);
                        #endregion
                        var toSave = getFileName(path, postFile);
                        IAsyncResult result = ImageHelper.UploadDataAsync(bucketName, toSave, bytes);
                        if (result.IsCompleted)
                        {
                            var img = new kmImages()
                            {
                                ID = Guid.NewGuid(),
                                Title = postFile.FileName,
                                Url = toSave,
                                BucketName = bucketName,
                            };
                            imgList.Add(img);
                        }
                    }
                }
                if (imgList.Count > 0)
                {
                    using (var dc = new ActivityEntities())
                    {
                        dc.kmImages.AddRange(imgList);
                        dc.SaveChanges();
                    }

                }
                IList<KmImgVO> imgVOs = new List<KmImgVO>();
                foreach (var img in imgList)
                {
                    string _url = ImageHelper.GetOssUrl(bucketName, img.Url);
                    string imgId = img.ID.ToString();
                    imgVOs.Add(new KmImgVO { ImageId = imgId, Url = _url });
                }
                switch (imgVOs.Count)
                {
                    case 0:
                        Error("上传失败");
                        break;
                    case 1:
                        Success(imgVOs[0]);
                        break;
                    default:
                        Success(imgVOs);
                        break;
                }
                #endregion
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex);
            Error(ex.Message);
        }

    }
    /// <summary>
    /// 删除图片
    /// </summary>
    /// <param name="BiType">业务类型</param>
    /// <param name="Id">图片Id</param>
    /// <returns>1成功/0失败</returns>
    public void DeleteOSS()
    {
        try
        {
            string BiType = "INSPECTION";
            string Id = _httpReuqest["Id"];
            using (var dc = new ActivityEntities())
            {
                Guid guid = new Guid();
                if (!string.IsNullOrWhiteSpace(Id))
                {
                    guid = new Guid(Id);
                }
                var img = dc.kmImages.FirstOrDefault(i => i.ID == guid);
                if (img == null)
                {
                    Error("图片不存在", 404);
                }
                else
                {
                    if (!string.IsNullOrEmpty(BiType))
                    {
                        switch (BiType)
                        {
                            case "INSPECTION":
                                var model = dc.t_inspection_img.FirstOrDefault(c => c.Img_ID == img.ID);
                                if (model != null)
                                {
                                    dc.t_inspection_img.Remove(model);
                                    dc.SaveChanges();
                                }

                                break;
                            //case "SHOPTASK":
                            //    result = dc.t_task_detail_imglist.Where(t => t.ImgID == img.ID).Delete();
                            //    break;
                            default: break;
                        }

                    }
                    if (!string.IsNullOrWhiteSpace(img.BucketName))
                    {
                        //删除云服务器图片
                        var oss = ImageHelper.DeleteOssImg(img.BucketName, img.Url);
                    }
                    var img_model = dc.kmImages.FirstOrDefault(c => c.ID == img.ID);
                    if (img_model != null)
                    {
                        dc.kmImages.Remove(img_model);
                        dc.SaveChanges();
                    }
                    Success("删除成功");
                }

            }
        }
        catch (Exception ex)
        {
            Log.Error(ex);
            Error(ex.Message);
        }
    }

    /// <summary>
    /// 获取图片
    /// </summary>
    /// <param name="BiType"></param>
    /// <param name="Id"></param>
    /// <returns>URL</returns>
    public void GetImgOSS()
    {
        string id = _httpReuqest["Id"];
        string url = string.Empty;
        if (!string.IsNullOrWhiteSpace(id))
        {
            Guid Id = new Guid(id);
            using (var dc = new ActivityEntities())
            {
                var model = dc.kmImages.FirstOrDefault(c => c.ID == Id);
                if (model != null)
                {
                    url = ImageHelper.GetOssUrl(model.BucketName, model.Url);
                }
            }
        }
        if (!string.IsNullOrEmpty(url)) Success(url);
        else Error("未找到图片");

    }

    private static byte[] Bitmap2Byte(Bitmap bitmap)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            bitmap.Save(stream, ImageFormat.Jpeg);
            byte[] data = new byte[stream.Length];
            stream.Seek(0, SeekOrigin.Begin);
            stream.Read(data, 0, Convert.ToInt32(stream.Length));
            return data;
        }
    }

    #region 获取文件名
    private static string getFileName(string vPath, string fileName)
    {
        if (fileName.Contains("."))
        {
            var name = DateTime.Now.Ticks.ToString();
            var ss = fileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            return string.Format("{0}/{1}.{2}", vPath, name, ss.LastOrDefault()).Replace("//", "/");
        }
        return string.Format("{0}/{1}", vPath, fileName).Replace("//", "/");
    }


    private static string getFileName(string vPath, string fileName, string taskType)
    {
        if (fileName.Contains("."))
        {
            var name = DateTime.Now.Ticks.ToString();
            var ss = fileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            return string.Format("{0}/{1}_{2}.{3}", vPath, taskType, name, ss.LastOrDefault()).Replace("//", "/");
        }
        return string.Format("{0}/{1}", vPath, fileName).Replace("//", "/");
    }

    private static string getFileName(string vPath, HttpPostedFile postFile)
    {
        var name = DateTime.Now.Ticks.ToString();
        if (postFile.FileName.Contains("."))
        {
            var ss = postFile.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            return string.Format("{0}/{1}.{2}", vPath, name, ss.LastOrDefault()).Replace("//", "/");
        }
        return string.Format("{0}/{1}/{2}", vPath, name, postFile.FileName).Replace("//", "/");
    }
    #endregion
    /// <summary>
    /// 获取保存图片路径
    /// </summary>
    /// <param name="BiType">业务类型</param>
    /// <param name="Path">路径头</param>
    /// <returns></returns>
    private string GetSavaFilePath(string BiType)
    {
        string result = string.Empty;
        string path = "Inspection";
        switch (BiType)
        {
            //case "SHOPTASK":
            //    result = string.Format("{0}/{1}}", (path + "/" + DateTime.Now.ToString("yyyyMMdd")).Substring(9), this.UserId);
            //    break;
            case "INSPECTION":
                result = string.Format("{0}/{1}", path, DateTime.Now.ToString("yyyyMMdd"));
                break;
            default:
                result = string.Format("{0}/{1}", path, DateTime.Now.ToString("yyyyMMdd"));
                break;
        }
        return result;
    }
    #endregion
}